<template>
    <div :class="`tech-shop ${mode}`" @touchstart="handleTouchStart" @touchend="handleTouchEnd">
        <!-- 地址 -->
        <ShopLocation :mode="mode" :styleMode="styleMode" :theme="theme" />
        <ShopAd v-if="shopInfoData && shopInfoData.advertisements && shopInfoData.advertisements.length > 0" :adList="shopInfoData.advertisements" :mode="mode" :styleMode="styleMode" :theme="theme" />
        <!-- 附近自提点 -->
        <!-- <ShopContainer class="shop-column" name="附近自提点" :info="`距离2km`" direction="horizontal"  :mode="mode" :styleMode="styleMode" :theme="theme">
            <GoodsItem v-for="(goods, idx) in showListGoods(item.prod_ids, shopIndexColumnData.prods)" :isBrand="isBrandMode" :key="idx + '-goods-item'" :itemInfo="goods"  :mode="mode" :styleMode="styleMode" :theme="theme" />
        </ShopContainer> -->
        <!-- 广告 -->
        <template v-for="(item, index) in shopIndexColumnData.pages">
            <ShopContainer class="shop-column" :name="item.name" :key="index + '-column'" direction="horizontal"  :mode="mode" :styleMode="styleMode" :theme="theme">
                <GoodsItem
                    v-for="(goods, idx) in showListGoods(item.prod_ids, shopIndexColumnData.prods)"
                    :isBrand="isBrandMode"
                    :key="idx + '-goods-item'"
                    :itemInfo="goods"
                    :storeInfo="shopIndexLibraryInfo"
                    :isHaveAddIcon="true"
                    :mode="mode"
                    :styleMode="styleMode"
                    :theme="theme"
                />
            </ShopContainer>
        </template>
        <ShopTabList :mode="mode" :styleMode="styleMode" :theme="theme"/>
        <Bag :isSingle="true" :mode="mode" :styleMode="styleMode" :theme="theme" />
        <LocationFail ref="locationFail" @reAction="reLocation" />
    </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import ShopLocation from './components/ShopLocation';
import ShopAd from './components/ShopAd';
import ShopContainer from './components/ShopContainer';
import GoodsItem from './components/GoodsItem';
import ShopTabList from './components/ShopTabList';
import Bag from './bag/Bag';
import { TechPanel } from '@components/base';
import { LocationFail } from '@components/biz';

import EventBus from '@common/eventBus';
import { setTitle, redirectTo, repalceTo } from '@common/utils';
import { platformTruth, getLocation } from '@common/environment';
import { wxConfig } from '@common/oauth/wechat';
import { getWXConfig } from '@store/action';
import { SHOP_MODE_TYPE } from '@constants/shop';
import { getUiMode, getUiTheme, getUiStyleMode } from '@biztools/info';
import { DEFAULT_MODE, DEFAULT_THEME, DEFAULT_STYLE_MODE } from '@constants/style';
import logger from '@common/logger';
import { ClearTip, TipLoading } from '@common/tip';

export default {
    name: 'Shop', // 在线商城
    components: {
        ShopLocation,
        ShopAd,
        TechPanel,
        ShopContainer,
        GoodsItem,
        ShopTabList,
        Bag,
        LocationFail,
    },
    data() {
        return {
            // 获取设置的配置信息
            mode: getUiMode() || DEFAULT_MODE,
            theme: getUiTheme() || DEFAULT_THEME,
            styleMode: getUiStyleMode() || DEFAULT_STYLE_MODE,
        };
    },
    computed: {
        ...mapState({
            addressInfo: state => state.shopAddress.addressInfo,
            shopInfoData: state => state.shop.shopInfoData,
            shopIndexColumnData: state => state.shop.shopIndexColumnData,
            shopIndexLibraryInfo: state => { return { ...state.shop.shopIndexLibraryInfo, isMainWarehouseInfo: true }; },
        }),
        showListGoods() {
            return (ids, list) => {
                let result = [];
                for (let i = 0; i < ids.length; i++) {
                    result.push({
                        ...list.filter(item => item.id === ids[i])[0],
                    });
                }
                return result;
            };
        },
        isBrandMode() {
            return this.shopInfoData.operation_mode === SHOP_MODE_TYPE.brand;
        },
    },
    created() {
        setTitle('商城');
        EventBus.$on('RefreshBagData', async () => {
            logger.debugger('监听到刷新Bag数据');
            await this.getShopBagInfo();
        });
    },
    async mounted() {
        logger.info('Shop => 当前的位置信息为：', this.addressInfo);
        logger.info('Shop => 执行获取member信息');
        TipLoading('加载中');
        await this.getShopMemberInfo();
        logger.success('Shop => 获取会员信息成功！');
        await this.getShopCard();
        logger.success('Shop => 商城领卡操作完成！');
        // 获取地理位置
        if (this.addressInfo) {
            await this.getIndexDataAction();
            return;
        }
        const { isWechat, isWechatMini } = platformTruth();
        if (isWechat || isWechatMini) {
            const config = await getWXConfig();
            wxConfig(config, ['getLocation'], async () => {
                await this.getLocationInfo();
            });
        } else {
            await this.getLocationInfo();
        }
        ClearTip();
    },
    methods: {
        ...mapActions([
            'getShopMemberInfo',
            'getShopCard',
            'matchShopAddress',
            'getLibraryInfo',
            'getShopInfoData',
            'getShopIndexShelfNext',
            'getShopIndexGroups',
            'getShopIndexColumnData',
            'getOnlineShopCartData',
            'getOnlineShopCartInfo',
        ]),
        // 重新刷新地址，去除token等信息
        reLocation() {
            repalceTo('shop');
        },
        handleTouchStart(e) {
            const { changedTouches } = e;
            this.startY = changedTouches[0].pageY;
        },
        async handleTouchEnd(e) {
            const { changedTouches } = e;
            this.endY = changedTouches[0].pageY;
            const elements = document.querySelector('.tech-shop');
            let clientHeight = elements.clientHeight;
            let scrollHeight = elements.scrollHeight;
            let scrollTop = elements.scrollTop;
            let isBottom = clientHeight + scrollTop > scrollHeight - 30;
            if (this.startY - this.endY > 30) {
                isBottom && await this.getShopIndexShelfNext();
            }
        },
        // 获取位置信息
        async getLocationInfo() {
            let location = null;
            try {
                location = await getLocation();
                logger.success('Shop => 获取到的地址为：', location);
            } catch (error) {
                logger.error(error);
            }
            if (location) {
                this.location = location;
                // 匹配位置信息
                await this.matchShopAddress(location);
                // 匹配仓库信息
                await this.getIndexDataAction();
            } else {
                this.$refs.locationFail.show();
            }
        },
        async getIndexDataAction() {
            TipLoading('获取数据中');
            // 获取首页信息
            await this.getShopInfoData();
            // 匹配仓库信息
            await this.getLibraryInfo({ addressInfo: this.addressInfo, isMain: this.isBrandMode});
            logger.info('Shop => 是否是总部模式', this.isBrandMode);
            // 获取分组
            await this.getShopIndexGroups(this.isBrandMode);
            // 获取栏目信息
            await this.getShopIndexColumnData();
            ClearTip();
            // 获取商城购物袋
            this.getShopBagInfo().then(() => {
                logger.info('Shop => 获取购物袋信息完成');
            });
        },
        async getShopBagInfo() {
            logger.warn('更新购物袋数据');
            // 获取购物车数据
            await this.getOnlineShopCartData();
            if (this.addressInfo) {
                // 获取参数项匹配信息
                await this.getOnlineShopCartInfo({ addressInfo: this.addressInfo, isMain: this.isBrandMode });
            }
        },
    },
};
</script>

<style lang="less">
.tech-shop {
    background-color: @white;
    height: 100vh;
    overflow-x: hidden;
    .shop-column {
        .container-content {
            .p-l(@shop-gap-md);
        }
    }
    .mode-white();
}
</style>
